<template>

  <el-card >

  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/basicdata' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <a href="/basicdata">库存管理</a>
    </el-breadcrumb-item>
    <el-breadcrumb-item>库存调拨</el-breadcrumb-item>
  </el-breadcrumb>

  <br>
  <br>


<div style="border: 1px solid #ccc;margin: 10px;padding: 10px;">

      <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="调拨单号：">
      <el-input v-model="formInline.AllotId" placeholder="调拨单号" clearable style="width: 200px;"/>
    </el-form-item>

    <el-form-item label="调拨申请日期">
        <el-date-picker
        v-model="formInline.DataTime"
        type="date"
        placeholder="请选择日期"
        style="width: 200px;"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <el-form-item label="单据类型：">
      <el-select v-model="formInline.DocumentType" placeholder="请选择" class="full-width" style="width: 200px ;">
                <el-option label="请选择" value="" />
                <el-option label="待审批" value="待审批" />
                <el-option label="已完成" value="已完成" />
                <el-option label="驳回" value="驳回" />
                <el-option label="通过" value="通过" />
              </el-select>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="Seach">查询</el-button>
      <el-button type="primary" @click="OutForm">重置</el-button>
      <el-button type="primary" @click="dialogFormVisible=true">添加</el-button>
    </el-form-item>
  </el-form>
    </div>

</el-card>

<br>


<el-card >
<el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="序号" width="80" />
    <el-table-column prop="allotId" label="调拨单号" width="120" />
    <el-table-column prop="documentType" label="单据类型" width="120" />
    <el-table-column prop="applicationDate" label="调拨申请日期" width="120" />
    <el-table-column prop="transferType" label="调拨类型" width="100" />
    <el-table-column prop="openWareHouse" label="调出仓库" width="120" />
    <el-table-column prop="closeWareHouse" label="调入仓库" width="120" />
    <el-table-column prop="allotNumber" label="调拨数量" width="120" />
    <el-table-column prop="allotPrice" label="调拨金额" width="120" />
    <el-table-column prop="responsiblePerson" label="经办人" width="120" />
    <el-table-column prop="allocateGoods" label="调拨货品" width="120" />
    <el-table-column prop="preparedBy" label="制单人" width="120" />
    <el-table-column prop="prepareData" label="制单时间" width="120" />
    <el-table-column prop="auditor" label="审核人" width="120" />
    <el-table-column prop="remark" label="备注" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="delAllot(scope.row.allotId)">
          删除
        </el-button>
        <el-button link type="primary" size="small" @click="UpdatAllot(scope.row.allotId)">
          修改
        </el-button>
        <el-button link type="primary" size="small" @click="ApproveAllot(scope.row.allotId)">
          审核
        </el-button>
      </template>
    </el-table-column>
  </el-table>



  <table>
    <tr>
        <td>
            <el-pagination
      v-model:current-page="y.PageIndex"
      v-model:page-size="y.PageSize"
      :page-sizes="[2, 3, 5, 10]"
      layout="slot,total, sizes"
      :total="y.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
当前第{{ y.PageIndex }}/{{ y.totalPage }}
</el-pagination>
        </td>

        <td>
            <el-pagination
      v-model:current-page="y.PageIndex"
      v-model:page-size="y.PageSize"
      :page-sizes="[2, 3, 5, 10]"
      layout="slot, prev, pager, next"
      :total="y.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
<el-button @click="handleCurrentChange(1)">首页</el-button>
</el-pagination>
        </td>

        <td>
            <el-pagination
      v-model:current-page="y.PageIndex"
      v-model:page-size="y.PageSize"
      :page-sizes="[2, 3, 5, 10]"
      layout="slot, jumper"
      :total="y.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
    <el-button @click="handleCurrentChange(y.totalPage)">尾页</el-button>
</el-pagination>
        </td>
    </tr>
</table>

</el-card>

<!-- 添加盘点弹出框 -->
<el-dialog v-model="dialogFormVisible" title="添加调拨" width="1500px">
  <!-- 基础信息部分 -->
  <el-card class="basic-info-card">
    <div class="card-title">基础信息</div>
    <br>
    <el-form :model="formData" label-width="120px" label-position="right">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调拨单号" required>
            <el-input v-model="formData.allotId" placeholder="自动获取系统编号" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点类型">
            <el-select v-model="formData.transferType" placeholder="请选择" class="full-width">
              <el-option label="请选择" value="" />
              <el-option label="货品调拨" value="货品调拨" />
              <el-option label="库存预警" value="库存预警" />
              <el-option label="满仓逃离" value="满仓逃离" />
              <el-option label="其他调拨" value="其他调拨" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调拨申请日期" required>
            <el-date-picker
              v-model="formData.prepareData"
              type="datetime"
              placeholder="请选择日期时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出库仓库名称" required>
            <div class="flex-container">
              <el-select v-model="formData.openWareHouse" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialawarehouse" :key="s.warehouseid" :label="s.warehousename" :value="s.warehouseid" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库仓库名称" required>
            <div class="flex-container">
              <el-select v-model="formData.closeWareHouse" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialawarehouse" :key="s.warehouseid" :label="s.warehousename" :value="s.warehouseid" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经办人">
            <div class="flex-container">
               <el-input v-model="formData.responsiblePerson" placeholder="请输入"  />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="审核人" required>
            <div class="flex-container">
              <el-select v-model="formData.audit" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialaus" :key="s.id" :label="s.trueName" :value="s.id" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制单人">
            <div class="flex-container">
              <el-select v-model="formData.preparedBy" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialaus" :key="s.id" :label="s.trueName" :value="s.id" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <!-- 盘点明细部分 -->
  <el-card class="detail-card">
    <div class="card-header">
      <div class="card-title">调拨明细</div>
      <br>
      <div class="button-group">
        <el-button type="primary" @click="showDetailDialog = true">添加</el-button>
        <el-button @click="removeSelected">移除</el-button>
      </div>
    </div>
    
    <el-table :data="formData.latestSub" style="width: 100%" max-height="400">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="itemName" label="货品名称" width="120" />
      <el-table-column prop="itemId" label="货品编号" width="120" />
      <el-table-column prop="itemSpec" label="规格型号" width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="itmeTypeName" label="货品类型" width="120" />
      <el-table-column prop="" label="调出仓库当前库存" width="120" />
      <el-table-column prop="" label="调入仓库当前库存" width="120" />
      <el-table-column label="盘点库位" width="120">
        <template #default="scope">
          <el-select v-model="scope.row.warehouseId" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialaku" :key="s.librarylocationid" :label="s.librarylocationname" :value="s.librarylocationid" />
              </el-select>
        </template>
      </el-table-column>
      <el-table-column label="调拨数量" width="120">
        <template #default="scope">
          <el-input 
            v-model="scope.row.allotNumber" 
            placeholder="请输入数量" 
            @input="calculateProfitLoss(scope.row)"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="入库单价" width="120">
        <template #default="scope">
          <el-input 
            v-model="scope.row.price" 
            placeholder="50" 
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="调拨金额" width="120">
        <template #default="scope">
          {{ scope.row.allotMoney }}
        </template>
      </el-table-column>
      <el-table-column label="备注" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.remark" placeholder="请输入" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click.prevent="removeSelected(scope.$index)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
  
  </el-card>
  

  <div style="text-align: center; margin-top: 20px;">
    <el-button type="primary" @click="saveStocktaking">保存</el-button>
    <el-button @click="dialogFormVisible = false">取消</el-button>
  </div>
</el-dialog>




<!-- 货品选择弹出框 -->
<el-dialog
  title="选择货品"
  v-model="showDetailDialog"
  width="90%"
>
  <el-table
    :data="itemList"
    @selection-change="handleItemSelection"
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="itemid" label="货品编号" width="120" />
    <el-table-column prop="itemname" label="货品名称" width="150" />
    <el-table-column prop="itemspec" label="规格型号" width="120" />
    <el-table-column prop="unitid" label="单位" width="80" />
    <el-table-column prop="itmeTypeName" label="货品类型" width="120" />
    <el-table-column prop="purchaseprice" label="账面库存" width="120" />
    <el-table-column prop="outboundprice" label="账面金额" width="120" />
  </el-table>
  <div style="margin-top: 16px; text-align: right;">
    <el-button @click="showDetailDialog = false">取消</el-button>
    <el-button type="primary" @click="addSelectedItems">确定</el-button>
  </div>
</el-dialog>




<el-dialog v-model="approvefg" title="审批" width="500px">

<el-form-item label="单据类型：">
      <el-select v-model="app.documentType" placeholder="请选择" class="full-width" style="width: 200px ;">
                <el-option label="请选择" value="" />
                <el-option label="驳回" value="驳回" />
                <el-option label="通过" value="通过" />
              </el-select>
    </el-form-item>

    <el-button @click="ApproveAllots()">保存</el-button>
    <el-button @click="approvefg=false">取消</el-button>
</el-dialog>







</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { id } from 'element-plus/es/locales.mjs';
import { onMounted, reactive, ref } from 'vue';











onMounted(()=>{
    Seach();
    WareHouse();
    fetchItemList();
    xialauser();
    xialakuwei();
})

const xialaus=ref([{
    id:'',
    trueName:''
}])

const xialauser=()=>{
    axios.get("api/app/standing/user").then(res=>{
        xialaus.value=res.data.pageData
    })
}


const xialaku=ref([{
    librarylocationname:'',
    librarylocationid:''
}])
const xialakuwei=()=>{
    axios.get("api/app/location/location-list?pageindex=1&pagesize=100").then(res=>{
        xialaku.value=res.data.pageData
    })
}


const calculateProfitLoss = (row: any) => {
 
  row.allotMoney= (row.allotNumber * 50).toFixed(2);
  
};





const xialawarehouse=ref([{
  warehousename:'',
  warehouseid:''
}])

const WareHouse=()=>{
  axios.get("api/app/allot/ware-house").then(res=>{
xialawarehouse.value=res.data.data
  })
}



const formInline = reactive({
    AllotId: '',
    DocumentType: '',
    DataTime: ''
})
const OutForm=()=>{
   formInline.AllotId='',
   formInline.DocumentType= '',
   formInline.DataTime= ''
}

const tableData=ref([])

const y=reactive({
    PageIndex:1,
    PageSize:10,
    totalCount:0,
    totalPage:0
})

const Seach=()=>{
    axios.get("api/app/allot/ot",{params:{
        PageIndex:y.PageIndex,
        PageSize:y.PageSize,
        AllotId:formInline.AllotId,
        DocumentType:formInline.DocumentType,
        DataTime:formInline.DataTime,
    }}).then(res=>{
        if(res.data.code==200){
            tableData.value=res.data.pageData
            y.totalCount=res.data.totalCount
            y.totalPage=Math.ceil(y.totalCount/y.PageSize)
        }
    })
}

const delAllot=(id:any)=>{
ElMessageBox.confirm(
    '确定要删除吗！！！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
       axios.delete("api/app/allot/allot/"+id,{
  })
  .then(res=>{
      if(res.data.code==200)
      {
          ElMessage.success(res.data.message)
          Seach();
      }
      else
      {
          ElMessage.error(res.data.message)
      }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
   y.PageSize=val;
  Seach();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
   y.PageIndex=val;
  Seach();
}



const dialogFormVisible=ref(false);


const formData=ref({
  "allotId": "",
  "transferType": "",
  "documentType": "待审批",
  "openWareHouse": "",
  "closeWareHouse": "",
  "responsiblePerson": "",
  "preparedBy": "",
  "prepareData": "",
  "remark": "",
  "audit": "",
  "latestSub": [
    {
      "allotId": "",
      "commodityId": "",
      "warehouseId": "",
      "allotNumber": "",
      "allotMoney": "",
      "remark": ""
    }
  ]
})

// 控制弹窗显示
const showDetailDialog = ref(false)
// 货品列表
const itemList = ref([{
     
}]);
const selectedItems = ref([]);

// 获取货品列表
const fetchItemList = () => {
  axios.get('api/app/allot/item').then(res => {
      itemList.value = res.data.pageData;
  });
};

// 处理货品选择
const handleItemSelection = (val: any) => {
  selectedItems.value = val;
};


const ysb = ref('');
// 添加选中的货品到明细
const addSelectedItems = () => {
  const newItems = selectedItems.value.map((item: any) => ({
    allotId: ysb, // 使用当前表单的盘点单号
    itemId: item.itemid,
    itemName: item.itemname,
    itemSpec: item.itemspec,
    unit: item.unitid,
    itmeTypeName: item.itmeTypeName,
    commodityId: item.itemid,
    warehouseId: "",
    allotNumber: "",
    allotMoney: "",
    remark: ""
    
  }));

  // 合并去重
  const ids = new Set(formData.value.latestSub.map((i: any) => i.itemId));
  newItems.forEach((item: any) => {
    if (!ids.has(item.itemId)) {
      formData.value.latestSub.push(item);
    }
  });

  showDetailDialog.value = false;
  selectedItems.value = [];
};

// 移除选中项
const removeSelected = (index?: number) => {
  if (index !== undefined) {
    formData.value.latestSub.splice(index, 1);
  } else {
    // 移除所有选中的项
    // 这里可以添加多选删除逻辑
  }
};



const sub = '调拨单'
const Bianma = async () => {
  try {
    const res = await axios.post("api/app/dm_Encoderule/start-code?Formtypeid=" + sub);
    if (res.data.code === 200) {
      ysb.value = res.data.data; // 修正赋值操作符
      formData.value.allotId = res.data.data; // 同时更新表单数据
      console.log('获取到的编码:', ysb.value);
      return res.data.data;
    }
  } catch (error) {
    console.error('获取编码失败:', error);
    ElMessage.error('获取编码失败');
    return null;
  }
}

const isEdit = ref(false); // 是否为编辑状态
const editOod = ref('');   // 当前编辑的盘点单号



const UpdatAllot = async (allotid: any) => {
  isEdit.value = true;
  editOod.value = allotid;
  try {
    const res = await axios.post('api/app/allot/show-allot?Allot=' + allotid);
    console.log('API返回的原始数据:', res.data);
    
    if (res.data.code === 200) {
      // 回显基础信息 - 修正字段映射
      formData.value = {
        allotId: res.data.data.allotId || res.data.data.allotid || '',
        transferType: res.data.data.transferType || '',
        documentType: res.data.data.documentType || '待审批',
        openWareHouse: res.data.data.openWareHouse || res.data.data.openwarehouse || '',
        closeWareHouse: res.data.data.closeWareHouse || res.data.data.closewarehouse || '',
        responsiblePerson: res.data.data.responsiblePerson || res.data.data.responsibleperson || '',
        preparedBy: res.data.data.preparedBy || res.data.data.preparedby || '',
        prepareData: res.data.data.prepareData || res.data.data.preparedata || '',
        remark: res.data.data.remark || '',
        audit: res.data.data.audit ,
        latestSub: []
      };
      
      // 处理明细数据
      if (res.data.data.latestSub && Array.isArray(res.data.data.latestSub)) {
        // 获取所有货品信息
        const itemIds = res.data.data.latestSub.map((item: any) => item.itemId || item.commodityId).filter(Boolean);
        
        if (itemIds.length > 0) {
          const itemInfoRes = await axios.get('api/app/allot/item');
          const allItems = itemInfoRes.data.pageData || [];
          
          formData.value.latestSub = res.data.data.latestSub.map((item: any) => {
            const itemId = item.itemId || item.commodityId;
            const itemInfo = allItems.find((info: any) => info.itemid === itemId);
            
            return {
              allotId: allotid,
              commodityId: itemId,
              itemId: itemId,
              itemName: itemInfo ? itemInfo.itemname : (item.itemName || ''),
              itemSpec: itemInfo ? itemInfo.itemspec : (item.itemSpec || ''),
              unit: itemInfo ? itemInfo.unitid : (item.unit || ''),
              itmeTypeName: itemInfo ? itemInfo.itmeTypeName : (item.itmeTypeName || ''),
              warehouseId: item.warehouseId || item.storageLocationID || '',
              allotNumber: item.allotNumber || item.allotnumber || '',
              allotMoney: item.allotMoney || item.allotmoney || '',
              price: item.price || 100,
              remark: item.remark || ''
            };
          });
        } else {
          formData.value.latestSub = res.data.data.latestSub.map((item: any) => ({
            allotId: allotid,
            commodityId: item.itemId || item.commodityId || '',
            itemId: item.itemId || item.commodityId || '',
            itemName: item.itemName || item.itemname || '',
            itemSpec: item.itemSpec || item.itemspec || '',
            unit: item.unit || item.unitid || '',
            itmeTypeName: item.itmeTypeName || item.itemTypeName || '',
            warehouseId: item.warehouseId || item.storageLocationID || '',
            allotNumber: item.allotNumber || item.allotnumber || '',
            allotMoney: item.allotMoney || item.allotmoney || '',
            price: item.price || 100,
            remark: item.remark || ''
          }));
        }
      } else {
        formData.value.latestSub = [];
      }
      
      console.log('处理后的表单数据:', formData.value);
      dialogFormVisible.value = true;
    } else {
      ElMessage.error(res.data.message || '获取数据失败');
    }
  } catch (e) {
    console.error('获取数据失败:', e);
    ElMessage.error('获取数据失败');
  }
};

const saveStocktaking = async () => {
  if (!formData.value.openWareHouse || !formData.value.closeWareHouse) {
    ElMessage.warning('请选择仓库');
    return;
  }
  if(formData.value.openWareHouse == formData.value.closeWareHouse){
    ElMessage.warning('调拨的仓库不能相同');
    return;
  }

  if (formData.value.latestSub.length === 0) {
    ElMessage.warning('请选择货品');
    return;
  }

  // 验证明细数据
  for (let item of formData.value.latestSub) {
    if (!item.allotNumber ) {
      ElMessage.warning('请输入有效的调拨数量');
      return;
    }
  }

  try {
    let code = formData.value.allotId;
    // 新增时获取编码
    if (!isEdit.value) {
      code = await Bianma();
      if (!code) {
        ElMessage.error('获取调拨单号失败');
        return;
      }
      formData.value.allotId = code;
      formData.value.latestSub.forEach(item => {
        item.allotId = code;
      });
    }
    // 编辑时直接用已有的单号
    else {
      formData.value.latestSub.forEach(item => {
        item.allotId = code;
      });
    }
 let res;
    if (isEdit.value) {
      // 编辑
      res = await axios.put('/api/app/allot/allot', formData.value);
    } else {
      // 新增
      res = await axios.post('/api/app/allot/latest-allot', formData.value);
    }
    if (res.data.code === 200) {
      ElMessage.success('保存成功');
      dialogFormVisible.value = false;
      Seach();
      // 重置表单
      formData.value = {
       "allotId": "",
  "transferType": "",
  "documentType": "待审批",
  "openWareHouse": "",
  "closeWareHouse": "",
  "responsiblePerson": "",
  "preparedBy": "",
  "prepareData": "",
  "remark": "",
  "audit": "",
  "latestSub": [
    {
      "allotId": "",
      "commodityId": "",
      "warehouseId": "",
      "allotNumber": "",
      "allotMoney": "",
      "remark": ""
    }
  ]
      };
      isEdit.value = false;
      editOod.value = '';
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请重试');
  }
    
};
    
   
    //   formData.value = {
    //     "allotId": "",
    //     "transferType": "",
    //     "documentType": "",
    //     "openWareHouse": "",
    //     "closeWareHouse": "",
    //     "responsiblePerson": "",
    //     "preparedBy": "",
    //     "prepareData": "",
    //     "remark": "",
    //     "audit": "",
    //     "latestSub": []
    //   };

const app=ref({
  allotId:'',
  documentType:''
})
const approvefg =ref(false);  
const ApproveAllot=(id:any)=>{

 app.value.allotId=id
 
 console.log(app.value.allotId,id);
 
approvefg.value=true
}

const ApproveAllots=()=>{

 axios.post("api/app/allot/approve",app.value).then(res=>{
ElMessage.success('修改成功');
  approvefg.value=false
  Seach();
 })
}




</script>